package com.hepinghospital.user.ui.activity.home;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Layout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.GeneralScheduleAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.eventbus.BookingRegisterSuccess;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.graphic.graphicSelect.GraphicSelectActivity;
import com.hepinghospital.user.ui.dialog.OffLineDialogFragment;
import com.hepinghospital.user.ui.dialog.RulesDialogFragment;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.Doctor;
import com.rest.response.TeamDetailResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;

/**
 * 医生详情
 *
 * @author lzp
 * @date 2023/3/26
 */

public class DoctorDetailActivity extends BaseActivity {
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_hospital)
    TextView tvHospital;
    @BindView(R.id.tv_prescription_tag)
    TextView tvPrescriptionTag;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.btn_tuwen)
    TextView btnTuwen;
    @BindView(R.id.btn_cloud)
    TextView btnCloud;
    @BindView(R.id.rv_cloud)
    RecyclerView rvCloud;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_more)
    TextView btnMore;
    @BindView(R.id.iv_doctor_photo)
    ImageView ivDoctorPhoto;
    @BindView(R.id.iv_doctor_cloud)
    ImageView ivDoctorCloud;
    @BindView(R.id.tv_show_one)
    TextView tvShowOne;
    @BindView(R.id.tv_show_two)
    TextView tvShowTwo;
    @BindView(R.id.tv_show_three)
    TextView tvShowThree;
    @BindView(R.id.tv_go)
    TextView tvGo;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.schedule_container)
    RelativeLayout scheduleContainer;
    @BindView(R.id.tv_cloud_go)
    TextView tvCloudGo;
    @BindView(R.id.team_recyclerView)
    RecyclerView teamRecyclerView;
    @BindView(R.id.team_container)
    LinearLayout teamContainer;
    @BindView(R.id.iv_doctor_offline)
    ImageView ivDoctorOffline;
    @BindView(R.id.rv_schedule_info)
    RecyclerView rvScheduleInfo;

    List<Doctor.Schedule> list = new ArrayList<>();
    List<Doctor.GeneralSchedule> listOffline = new ArrayList<>();
    List<TeamDetailResponse> teamList = new ArrayList<>();
    String id;

    /*** 0 选中预约挂号 1 选中图文问诊  2 选中云门诊*/
    int type;
    MyAdapter adapter;
    TeamAdapter teamAdapter;
    Doctor doctor;
    /*** 是否支持云门诊*/
    private boolean isCloud = true;
    /*** 是否支持图文问诊*/
    private boolean isPhoto = true;
    /*** 是否有排班*/
    private boolean isWorkTime;
    private String feePhoto;
    private RulesDialogFragment mRulesDialogFragment;
    private GeneralScheduleAdapter generalScheduleAdapter;

    @Override
    protected void initViews() {
        rvScheduleInfo.setLayoutManager(new LinearLayoutManager(this));
        generalScheduleAdapter = new GeneralScheduleAdapter(this, listOffline);
        rvScheduleInfo.setAdapter(generalScheduleAdapter);
        generalScheduleAdapter.setOnItemClickLitener((view, position) -> {
            if (listOffline.get(position).isSchedule == 0) {
                ToastUtil.showToast(mContext, "已约满，请选择其他号源");
            } else {
                OffLineDialogFragment mOffLineDialogFragment = OffLineDialogFragment.newInstance(doctor.id, listOffline.get(position).deptId, listOffline.get(position).scheduledata, listOffline.get(position).timeInterval, listOffline.get(position).scheduleTime);
                mOffLineDialogFragment.setmListener((time, scheduleTime, id, price, number) -> {
                    if (TextUtils.isEmpty(id)) {
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("obj", doctor);
                    bundle.putString("numberId", id);
                    bundle.putString("time", time);
                    bundle.putString("scheduleTime", scheduleTime);
                    bundle.putString("price", price);
                    bundle.putString("number", number);
                    bundle.putString("deptName", listOffline.get(position).deptName);
                    startActivity(DailyCheckDetailActivity.class, bundle);
                    mOffLineDialogFragment.dismiss();
                });
                mOffLineDialogFragment.show(getSupportFragmentManager(), "OffLineDialogFragment");
            }
        });
        rvCloud.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyAdapter();
        rvCloud.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> initData());
        LinearLayoutManager manager2 = new LinearLayoutManager(this);
        manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        teamRecyclerView.setLayoutManager(manager2);
        teamAdapter = new TeamAdapter();
        teamRecyclerView.setAdapter(teamAdapter);
        teamRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.right = DpUtil.dip2px(DoctorDetailActivity.this, 1);
            }
        });
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra(UIConstants.DOCTORDETAILACTIVITY_TYPE_FLAG, 0);
        getDoctorDetail();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_doctor_detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void getDoctorDetail() {
        showLoadingDialog(mContext);
        RestProxy.getInstance().getDoctorDetail(id, new Observer<Doctor>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(Doctor doctorDetailResponse) {
                if (doctorDetailResponse.doctorTeamListDto.size() == 0) {
                    teamContainer.setVisibility(View.GONE);
                } else {
                    teamContainer.setVisibility(View.VISIBLE);
                    teamList.addAll(doctorDetailResponse.doctorTeamListDto);
                    teamAdapter.notifyDataSetChanged();
                }
                doctor = doctorDetailResponse;
                tvName.setText(doctorDetailResponse.docName);
                tvLevel.setText(doctorDetailResponse.deptName + " " + doctorDetailResponse.jobTitleName);
                tvHospital.setText(doctorDetailResponse.hospitalName);
//                tv_skill.setText("擅长疾病: " + doctorDetailResponse.docGoodAtNames);
                tvInfo.setText("个人简介: " + doctorDetailResponse.introduction);
                tvLevel.setText(doctorDetailResponse.jobTitleName);
                tvStar.setText(doctorDetailResponse.score);
//                ratingBar.setRating(Float.parseFloat(doctorDetailResponse.score));
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(DoctorDetailActivity.this, doctorDetailResponse.thumbnailUrl, imgHead);
                feePhoto = doctorDetailResponse.fee;
//                tvGo.setText( "图文问诊预约¥" + feePhoto + "元/次" );
                if (doctorDetailResponse.isPrescription == 1) {
                    tvPrescriptionTag.setVisibility(View.VISIBLE);
                } else {
                    tvPrescriptionTag.setVisibility(View.GONE);
                }
                if (!UtilList.isEmpty(doctorDetailResponse.generalScheduleList)) {
                    scheduleContainer.setVisibility(View.VISIBLE);
                    rvScheduleInfo.setVisibility(View.VISIBLE);
                    listOffline.clear();
                    listOffline.addAll(doctorDetailResponse.generalScheduleList);
                    generalScheduleAdapter.notifyDataSetChanged();
                } else {
                    scheduleContainer.setVisibility(View.GONE);
                    rvScheduleInfo.setVisibility(View.GONE);
                }

                isWorkTime = !UtilList.isEmpty(doctorDetailResponse.scheduleInfoDtoList);

                list.clear();
                list.addAll(doctorDetailResponse.scheduleInfoDtoList);
                adapter.notifyDataSetChanged();

                //0:图文咨询和云门诊 1：图文咨询 3:云门诊 4：都不是
                if (doctorDetailResponse.diagType == 1) {
                    btnCloud.setEnabled(false);
                    btnCloud.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                    isCloud = false;
                    tvCloudGo.setVisibility(View.GONE);
                } else if (doctorDetailResponse.diagType == 3) {
                    btnTuwen.setEnabled(false);
                    btnTuwen.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                    isPhoto = false;
                } else if (doctorDetailResponse.diagType == 4) {
                    isPhoto = false;
                    isCloud = false;
                }

                ivDoctorOffline.setImageDrawable(getDrawable(R.drawable.ic_appoint_checked));
                if (isPhoto) {
                    graphiConsultationChecked();
//                    ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_unchecked));
                } else {
                    ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_disable));
                }
                if (isCloud) {
                    ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_unchecked));
                } else {
                    ivDoctorCloud.setVisibility(View.GONE);
//                    ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_disable));
                }

                tvInfo.post(() -> {
                    Layout l = tvInfo.getLayout();
                    if (l != null) {
                        int lines = l.getLineCount();
                        Log.d("lines =====", lines + "");
                        if (lines > 0) {
                            if (l.getEllipsisCount(lines - 1) > 0) {
                                btnMore.setVisibility(View.VISIBLE);
                            } else {
                                btnMore.setVisibility(View.GONE);
                            }
                        }
                    } else {
                        Log.d("999", "Layout is null");
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dismissLoadingDialog();
                ToastUtil.onError(DoctorDetailActivity.this, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                dismissLoadingDialog();
                refreshLayout.finishRefresh(true);
            }
        });
    }


    @SuppressLint("SetTextI18n")
    @OnClick({R.id.iv_doctor_offline, R.id.iv_doctor_photo, R.id.iv_doctor_cloud, R.id.tv_go, R.id.tv_cloud_go, R.id.btn_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_doctor_offline:
                bookingRegisterChecked();
                break;
            case R.id.iv_doctor_photo:
                if (isPhoto) {
                    graphiConsultationChecked();
                }
                break;
            case R.id.iv_doctor_cloud:
                if (isCloud) {
                    cloudClinicChecked();
                }
                break;
            case R.id.tv_go:
                if (!isPhoto) {
                    ToastUtil.showToast(mContext, "该医生没开启图文问诊预约");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putSerializable(UIConstants.OBJ_Doctor, doctor);
                bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_0);
                startActivity(GraphicSelectActivity.class, bundle);

                break;
            case R.id.tv_cloud_go:
                if (!isCloud || !isWorkTime) {
                    ToastUtil.showToast(mContext, "该医生没开启云门诊预约");
                    return;
                }

                Bundle bundleCloud = new Bundle();
                bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctor);
                bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                startActivity(PayActivity.class, bundleCloud);
                break;
            case R.id.btn_more:
                if (tvInfo.getMaxLines() == 2) {
                    btnMore.setText("点击收起>");
                    tvInfo.setMaxLines(100);
                } else {
                    btnMore.setText("查看全部>");
                    tvInfo.setMaxLines(2);
                }
            default:
                break;
        }
    }

    @Subscribe
   public void onEvent(BookingRegisterSuccess bookingRegisterSuccess) {
        finish();
    }

    /*** 选择云门诊*/
    private void cloudClinicChecked() {
        if (isWorkTime) {
            scheduleContainer.setVisibility(View.VISIBLE);
            rvCloud.setVisibility(View.VISIBLE);
        } else {
            scheduleContainer.setVisibility(View.GONE);
            rvCloud.setVisibility(View.GONE);
        }
        rvScheduleInfo.setVisibility(View.GONE);
        ivDoctorOffline.setImageDrawable(getDrawable(R.drawable.ic_appoint_unchecked));
        if (isPhoto) {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_unchecked));
        } else {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_disable));
        }
        if (isCloud) {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_checked));
        } else {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_disable));
        }
        tvShowOne.setText("预约线上门诊号源与医生视频沟通就诊");
        tvShowTwo.setText("到达预约时间在APP上报道后，等待医生开启视频");
        tvShowThree.setText("视频未接通可申请退款");
        tvGo.setVisibility(View.GONE);
        tvCloudGo.setVisibility(View.VISIBLE);
        //                scrollView.fullScroll( ScrollView.FOCUS_UP);
    }

    /*** 选择图文问诊*/
    private void graphiConsultationChecked() {
        ivDoctorOffline.setImageDrawable(getDrawable(R.drawable.ic_appoint_unchecked));
        if (isPhoto) {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_checked));
        } else {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_disable));
        }
        if (isCloud) {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_unchecked));
        } else {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_disable));
        }
        tvGo.setText("图文问诊预约¥" + feePhoto + "元/次");
        tvShowOne.setText("使用图片、文字与医生线上沟通");
        tvShowTwo.setText("医生24小时内未接诊自动全额退款");
        tvShowThree.setText("问诊服务需双方确认后结束");
        scheduleContainer.setVisibility(View.INVISIBLE);
        rvScheduleInfo.setVisibility(View.GONE);
        rvCloud.setVisibility(View.GONE);

        tvGo.setVisibility(View.VISIBLE);
        tvCloudGo.setVisibility(View.GONE);
        scrollView.fullScroll(ScrollView.FOCUS_UP);
    }

    /*** 选择预约挂号*/
    private void bookingRegisterChecked() {
        if (!UtilList.isEmpty(listOffline)) {
            scheduleContainer.setVisibility(View.VISIBLE);
            rvScheduleInfo.setVisibility(View.VISIBLE);
        } else {
            scheduleContainer.setVisibility(View.GONE);
            rvScheduleInfo.setVisibility(View.GONE);
        }
        rvCloud.setVisibility(View.GONE);
        ivDoctorOffline.setImageDrawable(getDrawable(R.drawable.ic_appoint_checked));
        if (isPhoto) {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_unchecked));
        } else {
            ivDoctorPhoto.setImageDrawable(getDrawable(R.drawable.ic_graph_disable));
        }
        if (isCloud) {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_unchecked));
        } else {
            ivDoctorCloud.setImageDrawable(getDrawable(R.drawable.ic_cloud_disable));
        }
        tvShowOne.setText("预约医生门诊号源");
        tvShowTwo.setText("线上预约、院内取号就诊");
        tvShowThree.setText("预约前请仔细阅读挂号须知");
        tvGo.setVisibility(View.GONE);
        tvCloudGo.setVisibility(View.GONE);
    }

    /**
     * 预约日期选择
     */
    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(DoctorDetailActivity.this).inflate(R.layout.item_schedule, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.tv_scheduleTime.setText(list.get(position).scheduleTime);
            holder.tv_dateTime.setText(list.get(position).dateTime);
            holder.tv_regFee.setText(list.get(position).deptName);

            if (list.get(position).isSchedule == 0) {
                holder.btn_confirm.setText("已约满");
//                holder.btn_confirm.setBackgroundResource( R.drawable.shape_grey );
                holder.btn_confirm.setTextColor(Color.parseColor("#ffd5d5d5"));
            } else {
                holder.btn_confirm.setText("可预约");
//                holder.btn_confirm.setBackgroundResource( R.drawable.selector_button );
                holder.btn_confirm.setTextColor(Color.parseColor("#ff209187"));
            }
            holder.btn_confirm.setOnClickListener(v -> {
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_scheduleTime, tv_dateTime, tv_regFee, btn_confirm;

            public Holder(View itemView) {
                super(itemView);
                tv_scheduleTime = itemView.findViewById(R.id.tv_scheduleTime);
                tv_dateTime = itemView.findViewById(R.id.tv_dateTime);
                tv_regFee = itemView.findViewById(R.id.tv_regFee);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
            }
        }
    }


    class TeamAdapter extends RecyclerView.Adapter<TeamAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(DoctorDetailActivity.this).inflate(R.layout.item_team, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.tv_name.setText(teamList.get(position).name);
            holder.tv_detail.setText(teamList.get(position).description);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(DoctorDetailActivity.this, teamList.get(position).thumbnailUrl, holder.img_head);
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("id", teamList.get(position).id + "");
                startActivity(TeamDetailActivity.class, bundle);
            });
        }

        @Override
        public int getItemCount() {
            return teamList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_detail;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_detail = itemView.findViewById(R.id.tv_detail);
                img_head = itemView.findViewById(R.id.img_head);
            }
        }
    }

    /*** 查询规则*/
    @OnClick(R.id.schedule_container)
    void queryProtocol() {
        showRulesDialogFragment();
    }


    private void showRulesDialogFragment() {
        mRulesDialogFragment = RulesDialogFragment.newInstance("6");
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }
}
